#ifndef LINUX_UDP_SOCKET_HPP
#define LINUX_UDP_SOCKET_HPP
#include "env.h"
#include <sys/socket.h>
#include <arpa/inet.h>
#include <netinet/in.h>
#include <stdio.h>
#include <unistd.h>
#include <string.h>

class linuxSocket {
  public:
    linuxSocket();
    ~linuxSocket();
    int Bind();
    int Resv(char *buffer, struct sockaddr_in *clnt_addr, socklen_t *clnt_addr_size);
    int Send(const char *buffer, int length, struct sockaddr_in *clnt_addr);
    int Close();
  private:
    int serv_sock;
    struct sockaddr_in serv_addr;
    struct sockaddr_in clnt_addr;
};

linuxSocket::linuxSocket() {
  //创建套接字
  serv_sock = socket(AF_INET, SOCK_DGRAM, 0);
  //将套接字和IP、端口绑定
  memset(&serv_addr, 0, sizeof(serv_addr));  //每个字节都用0填充
  serv_addr.sin_family = AF_INET;  //使用IPv4地址
  serv_addr.sin_addr.s_addr = htonl(INADDR_ANY);  //具体的IP地址
  serv_addr.sin_port = htons(SERVER_PORT);  //端口
  Bind();
}

linuxSocket::~linuxSocket() {
  Close();
}

int linuxSocket::Bind() {
  bind(serv_sock, (struct sockaddr*)&serv_addr, sizeof(serv_addr));
  return 1;
}


int linuxSocket::Close() {
  close(serv_sock);
  return 1;
}

int linuxSocket::Resv(char *buffer, struct sockaddr_in *clnt_addr, socklen_t *clnt_addr_size) {
  ssize_t strLen = recvfrom(serv_sock, buffer, 512, 0, (struct sockaddr*)clnt_addr, clnt_addr_size);
  printf("iP: %s, port: %d\n", inet_ntoa(clnt_addr->sin_addr), ntohs(clnt_addr->sin_port));
  return 1;
}

int linuxSocket::Send(const char *buffer, int length, struct sockaddr_in *clnt_addr) {
  socklen_t clnt_addr_size = sizeof(*clnt_addr);
  sendto(serv_sock, buffer, length, 0, (struct sockaddr*)clnt_addr, clnt_addr_size);
  return 1;
}
#endif // LINUX_UDP_SOCKET_HPP